package com.hkd.user_api.strategy.upload;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.hkd.base_service.api.dto.AreaUploadDTO;
import com.hkd.common.api.SysException;
import com.hkd.common.api.enums.AreaType;
import com.hkd.common.api.constants.FileType;
import com.hkd.utils.CheckUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 省市区上传处理
 * 具体策略
 * @author HKD
 * @date 2022/9/11 12:25
 */
@Component
public class AreaUpload implements Upload<List<AreaUploadDTO>>{

    @Override
    public List<AreaUploadDTO> handler(MultipartFile file) {
        List<AreaUploadDTO> list=new ArrayList<>();
        try {
            check(file);
            InputStream inputStream = file.getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            int rowCount = reader.getRowCount();
            for (int i = 0; i < rowCount; i++) {
                AreaUploadDTO uploadDTO = new AreaUploadDTO();
                String name = (String) reader.readCellValue(0, i);
                String code=(String)reader.readCellValue(1,i);
                uploadDTO.setName(name);
                uploadDTO.setCode(code);
                AreaType areaType = CheckUtil.areaType(code);
                uploadDTO.setAreaType(areaType);
                list.add(uploadDTO);
            }
        } catch (IOException e) {
            throw new SysException(e.getMessage());
        } catch (Throwable e) {
            throw new SysException(e.getMessage());
        }
        return list;
    }

    /**
     * 文件格式检查
     * @param file
     * @return
     */
    private void check(MultipartFile file)  {
        String fileType = CheckUtil.fileType(file.getOriginalFilename());
        if (StringUtils.isEmpty(fileType)){
            throw new SysException("获取文件后缀失败");
        }
        boolean contains = FileType.EXCEL.contains(fileType);
        if (!contains){
            throw new SysException("文件格式不支持");
        }
    }
}
